Destructuring is a special syntax in JavaScript that allows you to unpack values from arrays or properties from objects into distinct variables. It makes your code more readable and concise.
You can extract values from arrays and assign them to variables:
const numbers = [1, 2, 3];
const [one, two, three] = numbers;
console.log(one); // 1
console.log(two); // 2
console.log(three); // 3
You can extract properties from objects and assign them to variables:
const person = { firstName: "Nitin", lastName: "Maurya" };
const { firstName, lastName } = person;
console.log(firstName); // Nitin
console.log(lastName); // Maurya
You can assign default values to variables if the unpacked value is undefined
:
const { a = 10, b = 5 } = { a: 3 };
console.log(a); // 3
console.log(b); // 5
You can destructure nested objects and arrays:
const person = {
name: "John",
address: {
city: "New York",
zip: "10001"
}
};
const { name, address: { city, zip } } = person;
console.log(name); // John
console.log(city); // New York
console.log(zip); // 10001
You can use the rest syntax to collect the remaining properties or elements:
const numbers = [1, 2, 3, 4, 5];
const [first, second, ...rest] = numbers;
console.log(first); // 1
console.log(second); // 2
console.log(rest); // [3, 4, 5]
For more detailed information, you can check out resources like MDN Web Docs and W3Schools.